<?php
/**
 * Created by PhpStorm.
 * User: alexey
 * Date: 6/2/14
 * Time: 8:12 PM
 */

namespace controller;

include_once("HTMLTemplate.php");

class HTMLTemplateUtil
{
  private static $templates;
  private static $files = array("cnf/html-templates.properties", "cnf/other-templates.properties");


  private static function getNameFromString($string)
  {
    $namePosStart = stripos($string, '\'') + 1;
    $namePosEnd = stripos($string, '\'', $namePosStart);
    $name = trim(substr($string, $namePosStart, $namePosEnd - $namePosStart));
    return $name;
  }

  private static function init()
  {
    self::$templates = new \SplObjectStorage();
    foreach (self::$files as $f) {
      $f = file($f);
      $tmpObjectStorage = self::parse($f);
      self::$templates->addAll($tmpObjectStorage);
    }
  }

  private static function parse($parseArray)
  {
    $tmpTemplateMap = new \SplObjectStorage();
    $arrayLength = count($parseArray);
    $template = "";
    $name = "";
    for ($i = 0; $i < $arrayLength; $i++) {
      $parseString = $parseArray[$i];
      if (!stripos($parseString, '/**')) {
        if (stripos($parseString, '!template')) {
          $name = self::getNameFromString($parseString);
        } else if (stripos($parseString, '/template')) {
          $templateInstance = new HTMLTemplate();
          $templateInstance->setKey($name);
          $templateInstance->setTemplate($template);
          $tmpTemplateMap->attach($templateInstance);
          $template = "";
          $name = "";
        } else {
          $template = $template . $parseString;
        }
      }
    }
    return $tmpTemplateMap;
  }

  private static function getTemplateByName($name)
  {
    if (!self::$templates) {
      self::init();
    }

    self::$templates->rewind();
    $count = self::$templates->count();
    for ($i = 0; $i < $count; $i++) {
      if (self::$templates->current()->getKey() == trim($name)) {
        return self::$templates->current()->getTemplate();
      }
      self::$templates->next();
    }
  }

  static function generateHTML($htmlName, $paramAssocArray)
  {
    $template = self::getTemplateByName($htmlName);
    $paramStartPos = 0;
    while ($paramStartPos = stripos($template, '{', $paramStartPos + 1)) {
      $paramStartPos += 1;
      $paramEndPos = stripos($template, '}', $paramStartPos);
      if ($paramEndPos) {
        $htmlParameter = substr($template, $paramStartPos, $paramEndPos - $paramStartPos);
        $template = str_replace("{" . $htmlParameter . "}", $paramAssocArray[$htmlParameter], $template);
      }
    }
    if (!empty($template)) {
      echo $template;
    } else {
      echo $htmlName;
    }
  }


} 